package io.github.veigara.tcp.framework.service;

//import io.github.veigara.tcpserver.handler.DeviceChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class DeviceService {

    private static final Logger logger = LoggerFactory.getLogger(DeviceService.class);

    @Autowired
    private DeviceConnectionService deviceConnService;

//    @Autowired
//    private DeviceChannelHandler deviceChannelHandler;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${server.port:9098}")
    private int serverPort;

    /**
     * 向指定设备发送消息
     */
    public boolean sendMessage(String deviceId, String message) {
        // 获取设备所在的服务器地址
//        String serverAddress = deviceConnService.getDeviceServer(deviceId);
//        if (serverAddress == null) {
//            logger.error("Device {} not found", deviceId);
//            return false;
//        }
//
//        // 检查是否是本地服务器
//        if (isLocalServer(serverAddress)) {
//            // 本地服务器直接发送消息
////            return deviceChannelHandler.sendMessageToLocalDevice(deviceId, message);
//            return true;
//        } else {
//            // 远程服务器需要转发消息
//            return forwardMessageToServer(deviceId, message, serverAddress);
//        }
        return true;
    }

    /**
     * 转发消息到目标服务器
     */
    private boolean forwardMessageToServer(String deviceId, String message, String serverAddress) {
        try {
            String url = "http://" + serverAddress + "/api/device/message/" + deviceId;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("deviceId", deviceId);
            requestBody.put("message", message);
            
            HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
            restTemplate.postForEntity(url, request, Void.class);
            return true;
        } catch (Exception e) {
            logger.error("Failed to forward message to device {} on server {}", deviceId, serverAddress, e);
            return false;
        }
    }

    /**
     * 检查是否是本地服务器
     */
    private boolean isLocalServer(String serverAddress) {
        // 实际实现应根据服务器IP和端口判断
//        String[] parts = serverAddress.split(":");
//        if (parts.length != 2) return false;
//
//        String host = parts[0];
//        int port = Integer.parseInt(parts[1]);
//
//        return ("localhost".equals(host) || "127.0.0.1".equals(host) || host.equals(getLocalIp()))
//                && port == serverPort;
        return true;
    }

    /**
     * 获取本地服务器IP
     */
    private String getLocalIp() {
        try {
            return java.net.InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            logger.error("Failed to get local IP", e);
            return "localhost";
        }
    }
}    